import java.util.HashMap;
import java.util.Map;

/**
 * @author 雷明浩
 * @date 2025/5/30 15:16
 */
public class PathSum {
    // leetcode 路径总和III
    // https://leetcode.cn/problems/path-sum-iii/description/?envType=study-plan-v2&envId=top-100-liked
    private Map<Long, Integer> map;
    public int pathSum(TreeNode root, int targetSum) {
        map = new HashMap<>();
        map.put(0L, 1);
        return dfs(root, targetSum, 0);
    }

    private int dfs(TreeNode root,  int targetSum, long sum) {
        if (root == null) {
            return 0;
        }
        sum += root.val;
        int count = map.getOrDefault(sum-targetSum, 0);
        map.put(sum, map.getOrDefault(sum,0)+1);
        count += dfs(root.left, targetSum, sum);
        count += dfs(root.right, targetSum, sum);
        map.put(sum, map.getOrDefault(sum,0)-1);
        return count;
    }
}